import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { viteMockServe } from 'vite-plugin-mock'

export default defineConfig(({ command, mode }) => {
  //检查process.cwd()路径下.env.development.local、.env.development、.env.local、.env这四个环境文件
  const env = loadEnv(mode, process.cwd())

  //返回vite配置
  return {
    plugins: [
      vue(),
      viteMockServe({
        mockPath: './src/mock',
        localEnabled: true, // 开发环境启用 Mock
        prodEnabled: false,
        logger: true,
        injectCode: `
          import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer'
          import mockModules from '../mock'
          createProdMockServer(mockModules)
        `
      })
    ],
    //解决“vite use `--host` to expose”
    base: './', //不加打包后白屏
    resolve: {
      //别名配置，引用src路径下的东西可以通过@如：import Layout from '@/layout/index.vue'
      alias: [
        {
          find: '@',
          replacement: resolve(__dirname, 'src')
        }
      ]
    },
    server: {
      host: '0.0.0.0',
      // 后缀
      port: 8800,
      // npm dev run 时自动打开浏览器
      open: true,
      proxy: {
        '/api': {
          target: env.VITE_API_URL,
          changeOrigin: true,
          ws: true,
          pathRewrite: {
            '^/api': ''
          }
        }
      }
    }
  }
})
